<template>
  <div>
    <a-input-search v-model="names" readOnly unselectable="on">
      <a-button
        @click.native="handlerSelect"
        slot="enterButton"
        :disabled="disabled"
        :icon="searchIcon ? 'search' : ''"
        >{{ searchIcon ? '' : searchBtnText || '选择用户' }}</a-button
      >
    </a-input-search>

    <!-- 查询窗口 -->
    <a-modal :title="title" :width="800" :visible="visible" destroyOnClose @ok="handleOk" @cancel="handleCancel" cancelText="关闭">
      <a-input-search
        v-model="searchValue"
        placeholder="输入姓名查找"
        @change="onChange"
        enter-button
      />
      <a-tree
        checkable
        :defaultExpandAll="true"
        :selectable="false"
        :loading="loading"
        :tree-data="treeData"
        :expanded-keys="expandedKeys"
        :auto-expand-parent="autoExpandParent"
        :checked-keys="checkedKeys"
        @expand="onExpand"
        @check="onCheck"
      >
        <template slot="title" slot-scope="{title}">
          <span v-if="title.indexOf(searchValue) > -1">
            {{ title.substr(0, title.indexOf(searchValue)) }}
            <span style="color: red;">{{ searchValue }}</span>
            {{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
          </span>
          <span v-else>{{ title }}</span>
        </template>
      </a-tree>
    </a-modal>
  </div>
</template>

<script>
import { getAction } from '@/api/manage'

export default {
  name: 'XUserTree',
  props: {
    value: [String, Number],
    text: String,
    showInfo: {
      type: Boolean,
      default: () => {
        return true
      }
    },
    multi: Boolean,
    searchIcon: Boolean,
    searchBtnText: String,
    disabled: Boolean,
    params:Object
  },
  data() {
    return {
      title:'查找用户',
      visible:false,
      loading: false,
      url: 'workflow/userTreeList',
      names: '',
      searchValue:'',
      ids:[],
      dataList:[],
      expandedKeys: [],
      checkedKeys: [],
      treeData: [],
      autoExpandParent:true,
      queryParam: Object.assign({},this.params)
    }
  },
  watch: {
    value:{
      handler(nv, ov) {
        this.ids = nv
        // if(nv&&nv!=ov){
        //   let ids = nv.split(',')
        //   this.loadData().then(res=>{
        //     this.setData(ids,'value')
        //   })
        // }
      },
      immediate:true
    },
    treeData:{
      handler(nv,ov){
        if(nv&&nv!=ov){
          this.generateList(nv)
        }
      }
    },
    text:{
      handler(to,from){
        this.names = to
      },
      immediate:true
    }
  },
  methods: {
    handlerSelect(){
      this.checkedKeys = []
      this.visible = true
      this.loadData().then(res=>{
        if(this.value){
          let ids = this.value.split(',')
          this.setData(ids,'value')
        }
      })
    },
    handleCancel(){
      this.checkedKeys = []
      this.expandedKeys = []
      this.visible = false
    },
    getCheckedData(checkedKeys,key='key'){
      let keys = [...new Set(checkedKeys)]
      let row = {}
      return this.dataList.filter(item=>{
        if(!row[item[key]]&&keys.indexOf(item[key])!=-1){
          row[item[key]] = item
          return true
        }else{
          return false
        }
      })
    },
    getParentKey (key, tree){
      let parentKey;
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.children) {
          if (node.children.some(item => item.key === key)) {
            parentKey = node.key;
          } else if (this.getParentKey(key, node.children)) {
            parentKey = this.getParentKey(key, node.children);
          }
        }
      }
      return parentKey;
    },
    generateList(data){
      for (let i = 0; i < data.length; i++) {
        const node = data[i];
        node.scopedSlots = { title: 'title' }
        this.dataList.push(node);
        if (node.children) {
          this.generateList(node.children);
        }
      }
    },
    handleOk() {
      this.setData(this.checkedKeys,'key')
      this.$emit('input',this.ids)
      this.$emit('change',this.ids)
      this.visible = false
    },
    setData(keys,valuekey){
      const checkedData =  this.getCheckedData(keys,valuekey)
      if(Array.isArray(checkedData)){
        let names = []
        let ids = []
        let keys = []
        checkedData.map(item=>{
          names.push(item.title)
          ids.push(item.value)
          // keys.push(item.key)
        })
        // this.checkedKeys = keys
        this.names = names.join(',')
        this.ids = ids.join(',')
      }
    },
    onCheck(checkedKeys, info) {
      this.checkedKeys = checkedKeys
    },
    onChange(e){
      const value = e.target.value;
      const expandedKeys = this.dataList
        .map(item => {
          if (item.title.indexOf(value) > -1) {
            return this.getParentKey(item.key, this.treeData);
          }
          return null;
        })
        .filter((item, i, self) => item && self.indexOf(item) === i);
      
      Object.assign(this, {
        expandedKeys,
        searchValue: value,
        autoExpandParent: true,
      });
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    loadData() {
      this.loading = true
      return getAction(this.url, this.queryParam).then(res => {
        if (res.success && res.result) {
          this.treeData = res.result
        } else {
          this.treeData = []
        }
      }).finally(()=>{
        this.loading = false
      })
    }
  }
}
</script>

<style scoped></style>
